package cn.tedu.blog.server.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 阿里云短信客户端组件类
 */
@Component
@Data
@ConfigurationProperties(prefix = "spring.sms")
public class SmsClient {

    private String accessKeyId; //AccessKey ID

    private String accessKeySecret; //AccessKey Secret

    private String endpoint; //访问的域名

    private String signName; //短信签名

    private String templateCode; //短信模板编码

    /**
     * 发送短信验证码
     *
     * @param phoneNumber 手机号
     * @param code        验证码
     * @throws Exception
     */
    public void sendSmsCode(String phoneNumber, String code) throws Exception {
        // 构建短信配置
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        System.out.println("accessKeyId:"+accessKeyId);
        System.out.println("accessKeySecret"+accessKeySecret);
        // 访问的域名
        config.endpoint = endpoint;

        // 创建客户端
        Client client = new Client(config);

        // 构建短信内容
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName(signName)
                .setTemplateCode(templateCode)
                .setPhoneNumbers(phoneNumber)
                .setTemplateParam("{\"code\":"+code+"}");
        //发送短信
        client.sendSms(sendSmsRequest);
    }
}
